/* Copyright (C) 2010 Luca Piccinelli
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* 
 * File:   skin_train.cpp
 * Author: picci
 *
 * Created on December 5, 2010, 3:33 PM
 */

#include "imgops/skin/functions/skin_train.h"

using namespace cv;

namespace NAMESPACE{
    
void skin_train_nbayes_from_img(const Mat& src,
                                const Mat& mask,
                                NormalBayesModel& model,
                                CVT_SPACE cvt_space,
                                bool update){
    CV_Assert( src.rows  == mask.rows );
    CV_Assert( src.cols  == mask.cols );
    CV_Assert( mask.type() == DataType<uchar>::type);
    CV_Assert( src.type()  == DataType<Vec3b>::type);

    Mat cvt_src;
    cvtColor(src, cvt_src, cvt_space);

    int x = 0, y = 0;
    switch (cvt_space){
        case YCRCB:
            x = 1, y = 2;
            break;
        case HSV:
            x = 0, y = 1;
            break;
        default:
        	return;
    }

    Mat rensponses(src.rows * src.cols, 1, DataType<int>::type);
    Mat samples;
    MatConstIterator_<uchar> mask_it     = mask.begin<uchar>(),
                             mask_it_end = mask.end<uchar>();

    int *responses_row;
    bool good_sample = 0;
    for(int i = 0; mask_it != mask_it_end; mask_it++, i++){
       responses_row = rensponses.ptr<int>(i);
       responses_row[0] = *mask_it > 0;
       if(responses_row[0]) good_sample = true;
    }
    cvt_src.reshape(1, src.rows * src.cols).colRange(x, y + 1).convertTo(samples, DataType<int>::type);
    if(good_sample)model.train(samples, rensponses, update);
}

}
